import { type RouteRecordRaw, createRouter, createWebHistory } from 'vue-router';
import { useRouterStore } from '@/stores/modules/router';
import { getMenusTrees } from '@/api/common/system';

const routes: Array<RouteRecordRaw> = [
  {
    'path': '/Login',
    'name': 'Login',
    'component': () => import('@/views/login/index.vue'),
    'meta': { title: '登录页' }
  },
  { 
    path: '/:catchAll(.*)',
    component: () => import('@/views/not-found/notFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const useRouter = useRouterStore();
  const { routeArr, createRoutes } = useRouter;

  if (to.path !== '/Login') {
    if (!routeArr.length) {
      getMenusTrees().then(res => {
        useRouter.menuTree = res.data;
        createRoutes(res.data, router);
        next({ path: to.path, replace: true });
      }).catch(err => {
        console.log(err)
        next();
      })
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router
